package plugin

import (
	"bufio"
	"context"
	"log"
	"net/http"
	"strings"
	"sync"
	"time"

	"github.com/anfragment/zen/cfg"
)

type config interface {
	GetRespLists() []cfg.Resp
	AddRespList(list cfg.Resp) string
}

type ConfigServer struct {
	config config
}

func LoadConfig(config config) {

	var wg sync.WaitGroup
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	var configServer []cfg.Resp = []cfg.Resp{}
	for _, resp := range config.GetRespLists() {
		if resp.Type == "config-server" && resp.Enabled {
			configServer = append(configServer, resp)
		}
	}
	for _, cfgServer := range configServer {
		wg.Add(1)
		go func(url string, name string) {
			defer wg.Done()
			req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
			if err != nil {
				log.Printf("load config initialization: %v", err)
			}
			resp, err := http.DefaultClient.Do(req)
			if err != nil {
				log.Printf("load config initialization: %v", err)
			}
			defer resp.Body.Close()
			scanner := bufio.NewScanner(resp.Body)

			for scanner.Scan() {
				line := strings.TrimSpace(scanner.Text())
				if line == "" {
					continue
				}
				log.Printf("load config %v", line)
				loadResp := strings.Split(line, "@")

				respCfg := &cfg.Resp{
					Type:    loadResp[1],
					Host:    loadResp[0],
					Enabled: true,
					Name:    loadResp[0],
				}
				if !contains(config.GetRespLists(), *respCfg) {
					config.AddRespList(*respCfg)
				}
			}

		}(cfgServer.Host, cfgServer.Name)
	}
	wg.Wait()
}

func contains(items []cfg.Resp, match cfg.Resp) bool {
	containsFlag := false
	for _, item := range items {
		if match.Host == item.Host && item.Type != "config-server" {
			containsFlag = true
			break
		}
	}
	return containsFlag
}
